const connections = require("../app/database");
class UserService {
  // 根据账户查询user
  async getUserByName(name) {
    // const statement = `SELECT * FROM user WHERE name = ?;`;
    // const res = await connections.execute(statement, [name]);
    // console.log(res);

    const statement = `
    SELECT user.*,r.permission_id
FROM user user
LEFT JOIN role r ON user.role_id = r.id
where user.name=?;`;
    // const statement = `SELECT * FROM user WHERE name = ?;`;
    const result = await connections.execute(statement, [name]);
    console.log(result[0]);
    return result[0];
  }
  // 注册用户
  async createUser(user) {
    const { name, password, email, tel, role } = user;
    console.log(role);
    const statement = `INSERT INTO user (name,password,user_email,user_tel,role_id) VALUES (?,?,?,?,?)`;
    const result = await connections.execute(statement, [
      name,
      password,
      email,
      tel,
      +role,
    ]);
    // console.log(result);
    return result[0];
  }

  //获取用户列表 + 用户权限
  async getUserListService() {
    // console.log("ss");

    const statement = `SELECT user.id,user.name name,createAt,updateAt,  r.name role,r.des description,user.user_email email,user.user_tel tel
    FROM user user
    LEFT JOIN role r ON user.role_id = r.id;`;
    const result = await connections.execute(statement);
    // return (JSON.stringify(result[0]));
    return result[0];
  }

  // 获取用户总数
  async getUserNum() {
    const statement = `select COUNT(*) as total from user`;
    const result = await connections.execute(statement);
    // return (JSON.stringify(result[0]));
    return result[0][0];
  }

  async updateUser(id, user) {
    console.log(user);
    // console.log(id);
    const statement = `UPDATE user SET name =?,user_email=?,user_tel=?,role_id=? where id = ?;`;
    // console.log(1);
    const result = await connections.execute(statement, [
      user.name,
      user.email,
      user.tel,
      +user.role,
      id,
    ]);
    // return (JSON.stringify(result[0]));
    // console.log(result);
    return result;
  }

  async deleteUserById(id) {
    const statement = `DELETE FROM user WHERE id = ?;`;
    const result = await connections.execute(statement, [id]);
    return result;
  }
}
module.exports = new UserService();
